<template>
  <div class="login">
    <el-form 
        v-loading="loading"
        element-loading-text="正在登录……"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0,0,0,0.8)"
        :rules="rules" 
        ref="loginForm" 
        :model="loginForm" 
        class="loginContainer">
      <!-- 标题 -->
      <h3 class="loginTitle">系统登录</h3>
      
      <!-- 用户名 -->
      <el-form-item prop="mobile">
        <el-input @blur="check_username" type="text" v-model="loginForm.mobile" auto-complete="false" placeholder="请输入用户名或手机号"></el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input type="password" v-model="loginForm.password" auto-complete="false" placeholder="请输入密码"></el-input>
      </el-form-item>

      <el-checkbox class="loginRemember" v-model="checked">记住我</el-checkbox>
      <el-button type="primary" style="width:100%" @click="submitLogin">登录</el-button>
    </el-form>
  </div>
</template>

<script>
import {postRequest} from "../utils/api"

export default {
  data(){
    return{ 
      loginForm:{
        mobile:'',
        password:'',
      },
      loading:false,
      checked:false,
      rules:{
        username:[{required:true, message:'请输入用户名或手机号',trigger:'blur'}],
        password:[{required:true, message:'请输入密码',trigger:'blur'}],
      }
    }
  },
  created() {
    // console.log(11)
  },
  methods:{
    submitLogin(){
      this.$refs.loginForm.validate((valid) => {
        if(valid){
          // alert('submit');
          this.loading = true
          postRequest('/login', this.loginForm).then(resp => {
            if(resp){
              
              //存储用户token
              const tokenStr = resp.data
              console.log(resp)
              window.sessionStorage.setItem('tokenStr', tokenStr)
              this.$router.push('/profile')
            }
           
          }).finally(() => {
            this.loading = false
            
          })
        }else{
          this.$message.error('请输入所有字段');
          return false;
        }
      })
    },
    // 检查用户名
    check_username: function () {
        var re = /^[a-zA-Z0-9_-]{5,20}$/;
        var re2 = /^[0-9]+$/;
        if (re.test(this.mobile) && !re2.test(this.mobile)) {
            this.error_name = false;
        } else {
            this.error_name_message = '请输入5-20个字符的用户名且不能为纯数字';
            this.error_name = true;
        }
        
    },
  }
}
</script>